json = require "json"

local enc_num = argv[1] or '';
url = "http://127.0.0.1:8763/api/phone/getRealNumber?encryptedPhone=" .. enc_num
api = freeswitch.API()


function uriencode(vals)
    -- Lua uriencode function
    --
    -- Can take a table, or a string of comma separated values.
    -- Examples:
    -- > print(uriencode("this=is,a=/test/,string='quotes'"))
    -- a=%2Ftest%2F&string=%27quotes%27&this=is
    -- > print(uriencode({this="is", a="/test/", string="'quotes'"}))
    -- a=%2Ftest%2F&string=%27quotes%27&this=is
    --
    function escape (s)
        s = string.gsub(
            s,
            '([\r\n"#%%&+:;<=>?@^`{|}%\\%[%]%(%)$!~,/\'])',
            function (c)
                return '%'..string.format("%02X", string.byte(c));
            end
        );
        s = string.gsub(s, "%s", "+");
        return s;
    end

    function encode (t)
        local s = "";
        for k , v in pairs(t) do
            s = s .. "&" .. escape(k) .. "=" .. escape(v);
        end
        return string.sub(s, 2);
    end

    if type(vals) == 'table' then
        return encode(vals);
    else
        local t = {};
        for k, v in  string.gmatch(vals, ",?([^=]+)=([^,]+)") do
            t[k]=v;
        end
        return encode(t);
    end
end

function decryptNumber()
	session:setVariable("curl_timeout", "2")
	session:execute("curl", url)
	local response_code = session:getVariable("curl_response_code")
	local response_data = session:getVariable("curl_response_data")
	if(response_code ~= "200") then
		return ""
	end
	freeswitch.consoleLog("INFO", "========= decryptResult: " .. response_data .. "\n")
	local res = json.decode(response_data)
    if(res['code'] ~= 200) then
            return ""
    end
    -- 号码长度<=10，且包含110,119,120等数字的，不外呼
    local realNumber = res["data"];
    if (string.len(realNumber) <= 10) then
        if string.find(realNumber, "110") then
            return ""
        end
        if string.find(realNumber, "119") then
            return ""
        end
        if string.find(realNumber, "120") then
            return ""
        end
    end
	return realNumber
end

local original_number = decryptNumber()
if original_number ~= "" then
    session:setVariable("original_number", original_number)
else
    session:execute("respond", "699 Decrypt Failed")
end

